package com.example.service.common;

import com.alibaba.fastjson.JSON;
import com.example.pojo.KUser;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * @author panghu
 * @version 1.0.0
 * @createTime 2023年09月09日 21:58:00
 * @Description
 */
@Component
@Slf4j
public class ElasticSynServiceImpl implements IDataSynchronousService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public void insertData(KUser kUser) {
        IndexRequest indexRequest = new IndexRequest("users");
        String userJsonString = JSON.toJSONString(kUser);
        indexRequest.id(kUser.getId().toString());
        indexRequest.source(userJsonString, XContentType.JSON);
        try {
            IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            log.info("操作状态:" + indexResponse.status());
        } catch (IOException e) {
            log.error("操作elastic出现异常: {}", e.getMessage());
        }
    }

    @Override
    public void updateData(KUser before, KUser after) {
        UpdateRequest updateRequest = new UpdateRequest("users",after.getId().toString());
        String userJsonString = JSON.toJSONString(after);
        updateRequest.doc(userJsonString,XContentType.JSON);
        try {
            UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
            log.info("操作状态:" + updateResponse.status());
        } catch (IOException e) {
            log.error("操作elastic出现异常: {}", e.getMessage());
        }
    }

    @Override
    public void deleteData(KUser kUser) {
        DeleteRequest deleteRequest = new DeleteRequest("users",kUser.getId().toString());
        try {
            DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            log.info("操作状态:" + deleteResponse.status());
        } catch (IOException e) {
            log.error("操作elastic出现异常: {}", e.getMessage());
        }
    }
}
